package com.itheima.ydd.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.dto.SysMenuDto;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.mapper.SysMenuMapper;
import com.itheima.ydd.service.SysMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuMapper menuMapper;


    /**
     * 查询所有菜单
     *
     * @return
     */
    @Override
    public List<SysMenuDto> getAllData() {
        List<SysMenu> menuList = menuMapper.selectByPid(0);

        List<SysMenuDto> sysMenuDtos = menuList.stream().map(menu -> {
            SysMenuDto menuDto = new SysMenuDto();
            BeanUtils.copyProperties(menu, menuDto);
            //递归查询
            this.childrenDto(menuDto);

            return menuDto;
        }).collect(Collectors.toList());

        return sysMenuDtos;
    }

    /**
     * 递归算法
     *
     * @param menuDto
     */
    private void childrenDto(SysMenuDto menuDto) {
        Integer menuDtoId = menuDto.getId();
        List<SysMenu> sysMenus = menuMapper.selectByPid(menuDtoId);

        if (sysMenus.isEmpty()) {
            return;
        }
        List<SysMenuDto> sysMenuDtos = sysMenus.stream().map(menu -> {
            SysMenuDto dto = new SysMenuDto();
            BeanUtils.copyProperties(menu, dto);

            childrenDto(dto);
            return dto;
        }).collect(Collectors.toList());
        menuDto.setChildren(sysMenuDtos);
    }



}
